//
//  SXHRedirectRequestUrlProtocol.m
//  ZLZKBaseUtils
//
//  Created by sxh on 2021/4/11.
//

#import "SXHRedirectRequestUrlProtocol.h"
#import "URLProtocolHandler.h"
#import "BaseTools.h"

#define DICT_OBJ_FOR_K(key) My_objectForKey:(key) File:__FILE__ Line:__LINE__

static NSString* const SXHRedirectRequestUrlProtocolKey = @"SXHRedirectRequestUrlProtocol";

@interface SXHRedirectRequestUrlProtocol()
<
    NSURLSessionDelegate,
    NSURLSessionDataDelegate
>

@property (nonatomic, strong) NSURLSessionDataTask *task;

@end

@implementation SXHRedirectRequestUrlProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    NSLog(@"request.URL.absoluteString = %@",request.URL.absoluteString);
    NSString *scheme = [[request URL] scheme];
    if ( (/*[scheme caseInsensitiveCompare:@"http"]  == NSOrderedSame ||*/
          [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame /*||
          [scheme caseInsensitiveCompare:@"mobileProxy"] == NSOrderedSame*/ ))
    {
        // 处理过了不再处理 避免无限循环
        if ([NSURLProtocol propertyForKey:SXHRedirectRequestUrlProtocolKey inRequest:request]) {
            return NO;
        }
        return YES;
    }
    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
    NSLog(@"%@",request.HTTPMethod);
    
    NSLog(@"url ---[%@]\n\n",request.URL.absoluteString);
    
    //读取配置文件
    NSDictionary *replace = (NSDictionary *)[[[URLProtocolHandler shared] configure] DICT_OBJ_FOR_K(@"replace")];
    
    NSArray *set = replace.allKeys;
    
    if ([set containsObject:request.URL.absoluteString]) {
        //线程安全
        NSRecursiveLock *lock = [[NSRecursiveLock alloc]init];

        [lock lock];
        
        NSString *fileName = [replace DICT_OBJ_FOR_K(request.URL.absoluteString)];
        
        //request截取重定向
        NSString *filePath = [[[URLProtocolHandler shared] bundle] pathForResource:fileName ofType:@""];
        
        // 两边任意一边取到了再重新设置request
        if (filePath != nil) {
            
            NSURL * url = [NSURL fileURLWithPath:filePath];
            mutableReqeust.URL = url;
        }
        
        [lock unlock];
    }

    return mutableReqeust;
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
    return [super requestIsCacheEquivalent:a toRequest:b];
}

- (void)startLoading{
    
    NSMutableURLRequest* request = self.request.mutableCopy;
    [NSURLProtocol setProperty:@YES forKey:SXHRedirectRequestUrlProtocolKey inRequest:request];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    self.task = [session dataTaskWithRequest:self.request];
    [self.task resume];
    

}
- (void)stopLoading
{
    if (self.task != nil) {
        [self.task cancel];
    }
}

//获取资源bundle
+ (NSBundle *)getBundle {
    
    NSString *mainStr = [[NSBundle mainBundle] bundlePath];
    
    NSString *moduleStr1 = [mainStr stringByAppendingPathComponent:@"ZLZKBaseUtils.bundle"];
    NSBundle *module1 = [NSBundle bundleWithPath:moduleStr1];
    
    NSString *moduleStr2 = [mainStr stringByAppendingPathComponent:@"Frameworks/ZLZKBaseUtils.framework/ZLZKBaseUtils.bundle"];
    NSBundle *module2 = [NSBundle bundleWithPath:moduleStr2];
    return module1 ?: module2;
}

#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
    
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [[self client] URLProtocol:self didLoadData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    [self.client URLProtocolDidFinishLoading:self];
}

@end
